<?php
class XKVDataFile {
    public $fp = null;
    public $file_heaer_info = 'XFrameworkKVFIle Ver 0.1';
    public function __construct($file_name) {
        $this->open($file_name);
    }
    public function open($file_name) {
        if(file_exists($file_name) && !is_file($file_name)) {
            throw new XException("can not open $file_name, it is not file");
        }
        if(!file_exists(dirname($file_name))) {
            throw new XException("$file_name parent directory not exist");
        }
        if(is_file($file_name)) {
            $this->fp = fopen($file_name,'r+b');
        } else {
            $this->fp = fopen($file_name, 'a+b');
            $this->init_file();
        }
    }
    public function read($key) {
    }
    public function init_file() {
        $header_str = str_pad($this->file_header_info,256);
        $header_str = pack('H',$header_str);
        fwrite($this->fp,$header_str);
        $key_buckets = str_pad('',10240);
        $key_buckets = pack('H',$key_buckets);
        fwrite($this->fp,$key_buckets);
    }
    public function write($key, $value) {
        $hash_key = getIndex($key);
        $hex_key = pack('H',$hash_key);
        $value = pack('H',$value);
        $len = strlen($value);
        fwrite($this->fp, $value);
    }
    public function getIndex($str_key) {
        $int_hash = 0;
        $key_len = strlen($str_key);
        for($i=0;$i<$key_len;$i++) {
            $int_hash = ((($int_hash <<5) + $int_hash) + ord($str_key[$i])) % 5813;
        }
        return $int_hash;
    }
}
